import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf

# 随机生成1000个点，分布在y=0.1x+0.3周围
num_points = 1000
vectors_set = []
for i in range(num_points):
    x1 = np.random.normal(0.0, 0.55)
    y1 = x1 * 0.1 + 0.3 + np.random.normal(0.0, 0.03)
    vectors_set.append([x1, y1])
# 生成样本点
x_data = [v[0] for v in vectors_set]
y_data = [v[1] for v in vectors_set]

# 生成1维的W矩阵，取值为[-1，1]之间的随机数
W = tf.Variable(tf.random_uniform([1], -1.0, 1.0), name='W')
# 生成1维的b矩阵，初始值为0
b = tf.Variable(tf.zeros([1]), name='b')
# 经过预算得出预估值
y = W * x_data + b

# 以预估值和实际值y_data之间差值作为损失
loss = tf.reduce_mean(tf.square(y - y_data), name='loss')
# 采用梯度下降优化参数
optimizer = tf.train.GradientDescentOptimizer(0.5)
# 训练的过程就是最小化这个误差值
train = optimizer.minimize(loss, name='train')

# 创建视图
sess = tf.Session()

init = tf.global_variables_initializer()
sess.run(init)

# 初始化的W和b是多少
print('W=', sess.run(W), 'b=', sess.run(b), 'loss=', sess.run(loss))

# 执行20次训练结果
for i in range(25):
    sess.run(train)
    # 输出训练好的W和b
    print('W=', sess.run(W), 'b=', sess.run(b), 'loss=', sess.run(loss))

plt.scatter(x_data, y_data, c='r')
plt.plot(x_data, sess.run(W)*x_data+sess.run(b), c='b')
plt.show()
